<template>
    <div class="student-container">
        <div class="nav-path">
            <span>一级分类</span> &gt; <span>二级分类</span>
        </div>

        <div class="content-card">
            <div class="card-header">
                <h2>学生管理</h2>
            </div>

            <div class="search-form">
                <div class="form-item">
                    <input v-model="searchForm.nameOrId" type="text" placeholder="学生姓名/学籍号" class="input-field" />
                </div>

                <div class="form-item">
                    <el-select v-model="searchForm.grade" placeholder="年级" clearable class="input-field">
                        <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>

                <div class="form-item">
                    <el-select v-model="searchForm.className" placeholder="班级" clearable class="input-field">
                        <el-option v-for="item in classOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>

                <div class="form-item">
                    <el-select v-model="searchForm.gender" placeholder="性别" clearable class="input-field">
                        <el-option v-for="item in genderOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>

                <div class="form-actions">
                    <el-button type="primary" @click="fetchStudentList">查 询</el-button>
                    <el-button @click="resetForm">重 置</el-button>
                </div>
            </div>

            <div class="operation-buttons">
                <el-button type="primary" @click="openAddDialog">
                    <i class="el-icon-plus"></i> 新增学生
                </el-button>
                <el-button @click="importStudents">
                    <i class="el-icon-upload"></i> 导入
                </el-button>
                <el-button @click="exportStudents">
                    <i class="el-icon-download"></i> 导出
                </el-button>
            </div>

            <div class="search-result">
                <div class="result-info">查询结果: 共计 {{ total }} 条数据</div>

                <el-table :data="studentList" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="studentName" label="学生姓名" min-width="120">
                        <template #default="scope">
                            <el-link type="primary" @click="viewStudent(scope.row)">{{ scope.row.studentName
                            }}</el-link>
                        </template>
                    </el-table-column>
                    <el-table-column prop="studentNumber" label="学籍号" min-width="150" />
                    <el-table-column prop="grade" label="年级" min-width="100" />
                    <el-table-column prop="className" label="班级" min-width="100" />
                    <el-table-column prop="genderDesc" label="性别" min-width="80" />
                    <el-table-column prop="createTime" label="创建时间" min-width="170" />
                    <el-table-column prop="updateTime" label="更新时间" min-width="170" />
                    <el-table-column label="操作" min-width="150" fixed="right">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="editStudent(scope.row)">
                                <i class="el-icon-edit"></i> 编辑
                            </el-button>
                            <el-button type="danger" size="small" @click="deleteStudent(scope.row)">
                                <i class="el-icon-delete"></i> 删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 添加/编辑学生对话框 -->
        <el-dialog :title="dialogType === 'add' ? '新增学生' : '编辑学生'" v-model="dialogVisible" width="50%">
            <el-form ref="studentForm" :model="studentForm" :rules="rules" label-width="100px">
                <el-form-item label="学生姓名" prop="studentName">
                    <el-input v-model="studentForm.studentName" />
                </el-form-item>
                <el-form-item label="学籍号" prop="studentNumber">
                    <el-input v-model="studentForm.studentNumber" />
                </el-form-item>
                <el-form-item label="年级" prop="grade">
                    <el-select v-model="studentForm.grade" placeholder="请选择年级" style="width: 100%">
                        <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="班级" prop="className">
                    <el-select v-model="studentForm.className" placeholder="请选择班级" style="width: 100%">
                        <el-option v-for="item in classOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="studentForm.gender" placeholder="请选择性别" style="width: 100%">
                        <el-option v-for="item in genderOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 数据定义
const studentList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const selectedRows = ref([]);
const studentForm = reactive({
    id: '',
    studentName: '',
    studentNumber: '',
    grade: '',
    className: '',
    classId: '',
    gender: '',
    createTime: '',
    updateTime: ''
});

// 表单验证规则
const rules = {
    studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
    studentNumber: [{ required: true, message: '请输入学籍号', trigger: 'blur' }],
    grade: [{ required: true, message: '请选择年级', trigger: 'change' }],
    className: [{ required: true, message: '请选择班级', trigger: 'change' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
};

// 搜索表单
const searchForm = reactive({
    nameOrId: '',
    grade: '',
    className: '',
    gender: ''
});

// 下拉选项
const gradeOptions = [
    { value: '一年级', label: '一年级' },
    { value: '二年级', label: '二年级' },
    { value: '三年级', label: '三年级' },
    { value: '四年级', label: '四年级' },
    { value: '五年级', label: '五年级' },
    { value: '六年级', label: '六年级' },
];

const classOptions = [
    { value: '1班', label: '1班' },
    { value: '2班', label: '2班' },
    { value: '3班', label: '3班' },
    { value: '4班', label: '4班' },
    { value: '5班', label: '5班' },
];

const genderOptions = [
    { value: '男', label: '男' },
    { value: '女', label: '女' },
];

// 初始化
onMounted(() => {
    fetchStudentList();
});

// 获取学生列表
const fetchStudentList = async () => {
    try {
        const params = {
            page: currentPage.value,
            size: pageSize.value,
            studentName: searchForm.nameOrId,
            studentNumber: searchForm.nameOrId,
            grade: searchForm.grade,
            className: searchForm.className,
            gender: searchForm.gender
        };

        // 使用POST请求与后端API匹配
        const response = await axios.post('/api/student/page', params);
        if (response.data.code === 200) {
            studentList.value = response.data.data.records || [];
            total.value = response.data.data.total || 0;
        } else {
            ElMessage.error(response.data.msg || '获取学生列表失败');
        }
    } catch (error) {
        console.error('获取学生列表出错:', error);
        ElMessage.error('获取学生列表失败，请稍后重试');
    }
};

// 重置搜索表单
const resetForm = () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = '';
    });
    fetchStudentList();
};

// 打开添加学生对话框
const openAddDialog = () => {
    dialogType.value = 'add';
    resetStudentForm();
    dialogVisible.value = true;
};

// 重置学生表单
const resetStudentForm = () => {
    Object.keys(studentForm).forEach(key => {
        studentForm[key] = '';
    });
};

// 编辑学生
const editStudent = (row) => {
    dialogType.value = 'edit';

    // 使用深拷贝避免直接修改原始数据
    Object.keys(studentForm).forEach(key => {
        studentForm[key] = row[key];
    });

    dialogVisible.value = true;
};

// 查看学生详情
const viewStudent = (row) => {
    editStudent(row); // 复用编辑功能，只是不允许修改
};

// 删除学生
const deleteStudent = (row) => {
    ElMessageBox.confirm(`确定要删除学生 ${row.studentName} 吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const response = await axios.delete(`/api/student/delete/${row.id}`);
            if (response.data.code === 200) {
                ElMessage.success('删除成功');
                fetchStudentList();
            } else {
                ElMessage.error(response.data.msg || '删除失败');
            }
        } catch (error) {
            console.error('删除学生出错:', error);
            ElMessage.error('删除失败，请稍后重试');
        }
    }).catch(() => {
        // 取消删除
    });
};

// 提交表单
const submitForm = async () => {
    try {
        if (dialogType.value === 'add') {
            // 添加学生
            const response = await axios.post('/api/student/add', studentForm);
            if (response.data.code === 200) {
                ElMessage.success('添加成功');
                dialogVisible.value = false;
                fetchStudentList();
            } else {
                ElMessage.error(response.data.msg || '添加失败');
            }
        } else {
            // 更新学生信息
            const response = await axios.put('/api/student/update', studentForm);
            if (response.data.code === 200) {
                ElMessage.success('更新成功');
                dialogVisible.value = false;
                fetchStudentList();
            } else {
                ElMessage.error(response.data.msg || '更新失败');
            }
        }
    } catch (error) {
        console.error('提交表单出错:', error);
        ElMessage.error('操作失败，请稍后重试');
    }
};

// 选择行变化
const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
};

// 页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page;
    fetchStudentList();
};

// 每页大小变化
const handleSizeChange = (size) => {
    pageSize.value = size;
    fetchStudentList();
};

// 导入学生
const importStudents = () => {
    ElMessage.info('导入功能开发中');
};

// 导出学生
const exportStudents = () => {
    ElMessage.info('导出功能开发中');
};
</script>

<style scoped>
.student-container {
    padding: 20px;
}

.nav-path {
    font-size: 14px;
    color: #606266;
    margin-bottom: 15px;
}

.content-card {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.card-header {
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 15px;
    margin-bottom: 20px;
}

.card-header h2 {
    font-size: 18px;
    color: #303133;
    margin: 0;
    font-weight: 500;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20px;
    gap: 10px;
}

.form-item {
    margin-right: 10px;
    margin-bottom: 10px;
}

.input-field {
    width: 200px;
}

.form-actions {
    margin-left: auto;
}

.operation-buttons {
    margin-bottom: 20px;
}

.search-result {
    margin-top: 20px;
}

.result-info {
    font-size: 14px;
    color: #909399;
    margin-bottom: 15px;
}

.el-pagination {
    margin-top: 20px;
    text-align: right;
}
</style>